<template>
  <div class="captcha-modal" v-if="visible">
    <div class="modal-mask"></div>
    <div class="modal-container">
      <div class="modal-header">
        <h3>验证</h3>
        <span class="close-btn" @click="closeModal">&times;</span>
      </div>
      <div class="modal-body">
        <div class="captcha-display">
          <img :src="captchaImage" @click="refreshCaptcha" alt="验证码" class="captcha-img">
          <span class="refresh-text" @click="refreshCaptcha">看不清？换一张</span>
        </div>
        <div class="input-group">
          <input
            type="text"
            v-model="userInput"
            placeholder="请输入验证码"
            @keyup.enter="verifyCaptcha"
            ref="inputField"
          >
          <button @click="verifyCaptcha" :disabled="verifying">
            {{ verifying ? '验证中...' : '确定' }}
          </button>
        </div>
        <div class="error-message" v-if="errorMessage">{{ errorMessage }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CaptchaModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 验证码API地址
    captchaApi: {
      type: String,
      default: '/captcha/image'
    },
    // 验证API地址
    verifyApi: {
      type: String,
      default: '/captcha/verify'
    }
  },
  data() {
    return {
      captchaImage: '',
      captchaText: '', // 实际验证码（从后端获取）
      userInput: '',
      verifying: false,
      errorMessage: ''
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.refreshCaptcha();
        this.$nextTick(() => {
          this.$refs.inputField.focus();
        });
      } else {
        this.resetForm();
      }
    }
  },
  methods: {
    // 获取验证码
     refreshCaptcha() {
      try {
        this.errorMessage = '';
        // 这里使用fetch API获取验证码图片
       this.$http.get("/captcha/image", {
          responseType: 'blob' // 确保正确接收二进制数据
        }).then(res => {
          // 创建图片URL
          this.captchaImage = URL.createObjectURL(res.data);
          // 从响应头获取验证码key
          const verificationKey = res.headers['verificationkey'];
          if (!verificationKey) throw new Error('缺少验证码标识');
          this.captchaText = verificationKey; // 存储key而非验证码本身
          }
        );
      } catch (error) {
        console.error('获取验证码失败:', error);
        this.errorMessage = '获取验证码失败，请重试';
      }
    },

    // 验证验证码
    async verifyCaptcha() {
      if (!this.userInput.trim()) {
        this.errorMessage = '请输入验证码';
        return;
      }

      this.verifying = true;
      this.errorMessage = '';

      try {
        // 调用验证接口
        const response = await this.$http.post(this.verifyApi, {
          code: this.userInput,       // 用户输入的验证码
          key: this.captchaText       // 从响应头获取的 verificationKey
        });

        // 根据后端返回结构判断验证结果
        if (response.data && response.data.code ==200) {
          this.$message.success('验证成功');
          this.$emit('custom-event')
          this.closeModal();
        } else {
          this.errorMessage = '验证码错误或失效';
          this.userInput = '';
          this.refreshCaptcha(); // 刷新验证码
        }
      }  finally {
        this.verifying = false;
      }
    },

    // 关闭弹窗
    closeModal() {
      this.$emit('update:visible', false);
      this.resetForm();
    },

    // 重置表单
    resetForm() {
      this.userInput = '';
      this.errorMessage = '';
      this.verifying = false;
      // 释放图片URL
      if (this.captchaImage) {
        URL.revokeObjectURL(this.captchaImage);
        this.captchaImage = '';
      }
    }
  },
  beforeDestroy() {
    // 组件销毁前释放资源
    if (this.captchaImage) {
      URL.revokeObjectURL(this.captchaImage);
    }
  }
};
</script>

<style scoped>
.captcha-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-container {
  position: relative;
  width: 400px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
  animation: modal-show 0.3s;
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.captcha-display {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.captcha-img {
  width: 150px;
  height: 50px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.refresh-text {
  margin-left: 15px;
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}

.refresh-text:hover {
  text-decoration: underline;
}

.input-group {
  display: flex;
}

.input-group input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  outline: none;
}

.input-group input:focus {
  border-color: #409eff;
}

.input-group button {
  padding: 0 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.input-group button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.error-message {
  margin-top: 10px;
  color: #f56c6c;
  font-size: 14px;
}

@keyframes modal-show {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
